package com.example.administrator.mvvm.module.login;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.example.administrator.mvvm.R;
import com.example.administrator.mvvm.databinding.ActivityLoginBinding;
import com.example.administrator.mvvm.module.user.UserActivity;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

/**
 * 登录页面
 */
public class LoginActivity extends RxAppCompatActivity {
    //DataBinding用来绑定UI和数据
    ActivityLoginBinding dataBinding;
    //用来处理登录相关的业务逻辑
    LoginViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        dataBinding.setLifecycleOwner(this);
        viewModel = new LoginViewModel(getApplication());
        //将activity_login的UI与该ViewModel绑定
        dataBinding.setViewModel(viewModel);

        //监听登录事件
        viewModel.getLoginLiveData().observe(this, new Observer<Boolean>() {

            @Override
            public void onChanged(@Nullable Boolean b) {
                if (b) {//登录成功
                    Intent intent = new Intent(LoginActivity.this, UserActivity.class);
                    startActivity(intent);
                } else {//登录失败
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
